<?php if(!defined('PUBLIC_DIR')) die('No Access!');

Cnamespace('System.Web.MVC');
class Trace implements iTrace{
	private static $DBHandler = NULL;
	private $Name;
	private $Uri;
	private $Event;
	private $Params = array();

	public function __construct($_name, Uri $_uri = null, Event $_event = null){
		if(!is_null($_uri) && is_a($_uri, 'Uri') && !is_null($_event) && is_a($_event, 'Event')){
			$this->Name = $_name;
			$this->Uri = $_uri;
			$this->Event = $_event;
		}else{
			if (self::$DBHandler == NULL)
				self::$DBHandler = Config::GetProvider();
			self::$DBHandler->Query("SELECT pattern, conditions, event FROM [Traces] WHERE name = '$_name' LIMIT 1;");
			$trace = self::$DBHandler->FetchArray();
			$this->Name = $_name;
			$this->Uri = new Uri($_name, $trace['pattern'], (array)unserialize($trace['conditions']));
			$this->Event = new Event($trace['event']);
		}
	}
	public function GetEvent(){
		return $this->Event;
	}
	public function GetParams(){
		return $this->Params;
	}
	public function Match($_referer){
		//Extract URL params
		preg_match_all('@:([\w]+)@', $this->Uri->getPattern(), $paramNames, PREG_PATTERN_ORDER);
		$paramNames = $paramNames[0];

		//Convert URL params into regex patterns, construct a regex for this route
		$patternAsRegex = $this->Uri->CreateRegex();
//var_dump($patternAsRegex);
		//Cache URL params' names and values if this route matches the current HTTP request
		if(preg_match($patternAsRegex, $_referer, $paramValues)){
			array_shift($paramValues);
			foreach($paramNames as $index => $value){
				if(isset($paramValues[substr($value, 1)])){
					$this->params[substr($value, 1)] = urldecode($paramValues[substr($value, 1)]);
				}
			}
			return True;
		}
		return False;
	}
	public function Dispath(){
		$this->Event->Execute($this->Params);
	}
}
